using System;
using System.Data;
using System.IO;
using System.Web;
using ECatalog.Models.Helpers;

namespace ECatalog.Models.Kits
{
    public class KitBuilder : IKitBuilder
    {
        private readonly IKitRepository kitRepository;

        private static string StorageRoot
        {
            get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); } //Path should! always end with '/'
        }

        public KitBuilder(IKitRepository kitRepository)
        {
            this.kitRepository = kitRepository;
        }

        public KitViewModel BuildVm(int kitId, int? organizationId)
        {
            return kitRepository.GetViewModel(kitId, organizationId);
        }

        public Kit Build(KitViewModel kitViewModel)
        {
            var k = new Kit
            {
                Description = kitViewModel.Description,
                KitId = kitViewModel.KitId,
                Sale = kitViewModel.Sale,
                SalePrice = kitViewModel.SalePrice,
                OrganizationId = kitViewModel.OrganizationId,
                ImageUrl = kitViewModel.ImageUrl,
                IsDeleted = kitViewModel.IsDeleted,
                KitModels = kitViewModel.KitModels,
                Organization = kitViewModel.Organization,
                TypeImage = kitViewModel.TypeImage
            };

            return k;
        }

        public void SaveFile(HttpPostedFileBase uploadedFile, Kit kit)
        {
            if (uploadedFile.ContentType.Equals("image/jpeg") || uploadedFile.ContentType.Equals("image/png") || uploadedFile.ContentType.Equals("image/gif"))
            {
                var file = uploadedFile;
                var fileName = String.Format("{0}-{1}", Guid.NewGuid(), file.FileName.ToLower());
                var trimName = fileName.Remove(fileName.LastIndexOf('.'));

                var path = Path.Combine(StorageRoot, "Organization-" + kit.OrganizationId.ToString(),
                                        "Kit-" + kit.KitId.ToString(), trimName);
                var path320 = Path.Combine(path, "320x240\\");
                var path800 = Path.Combine(path, "800x600\\");
                ImageHelper.CreateDirectory(path);
                ImageHelper.CreateDirectory(path320);
                ImageHelper.CreateDirectory(path800);

                if (Directory.Exists(path) && Directory.Exists(path320) && Directory.Exists(path800))
                {
                    ImageHelper.BuildImage(file, path320, fileName, 320, 240);
                    ImageHelper.BuildImage(file, path800, fileName, 800, 600);
                }
                kit.ImageUrl = trimName;
                kit.TypeImage = ImageHelper.GetImageType(uploadedFile.ContentType);
                kitRepository.SaveKit(kit);
            }
        }

        public void Save(Kit kit)
        {
            kitRepository.SaveKit(kit);
        }
    }
}